package com.beiing.tianshuai.tianshuai.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.util.ImgUtils;
import com.beiing.tianshuai.tianshuai.widget.ActionSheet;
import com.lzy.ninegrid.NineGridViewImgUtils;
import com.mic.etoast2.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by magikliu on 2017/9/19.
 */

public class ImageBrowserAdapter extends PagerAdapter implements ActionSheet.OnSheetItemClickListener{

    private static final String TAG = "ImageBrowserAdapter";
    private Activity context;
    private List<String> picUrls;
    private int picPosition;
    private File file;
    private String fileName;
    private String dirName;

    public ImageBrowserAdapter(Activity context, List<String> picUrls) {
        this.context = context;
        this.picUrls = picUrls;
    }

    @Override
    public int getCount() {
        return picUrls.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        View view = View.inflate(context, R.layout.item_image_browser, null);
        ImageView pvShowImage = (ImageView) view.findViewById(R.id.pv_show_image);

        String picUrl = picUrls.get(position);
        final PhotoViewAttacher photoViewAttacher = new PhotoViewAttacher(pvShowImage);
        photoViewAttacher.setScaleType(ImageView.ScaleType.FIT_CENTER);
        photoViewAttacher.setMinimumScale(1F);
        ImgUtils.displayScaleImage(context, pvShowImage, picUrl, photoViewAttacher);
        photoViewAttacher.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                showSaveMenu(context, position);
                return false;
            }
        });
        //设置轻触退出
        photoViewAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                context.finish();
            }
        });
        container.addView(view);
        return view;
    }

    private void showSaveMenu(Context context, int position) {
        picPosition = position;
        ActionSheet actionSheet = new ActionSheet(context);
        actionSheet.builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("保存图片", ActionSheet.SheetItemColor.Blue, this)
                .show();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public void onClick(int which) {
        switch (which){
            case 1:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        downLoad(picUrls.get(picPosition));
                    }
                }).start();
                Toast.makeText(context, "图片保存成功", 0).show();
                break;
        }
    }

    private void downLoad(String url) {
        try {
            URL picUrl = new URL(url);
            //打开连接
            URLConnection conn = picUrl.openConnection();
            //打开输入流
            InputStream is = conn.getInputStream();
            //获得长度
            int contentLength = conn.getContentLength();
            //创建文件夹，在存储卡下
            dirName = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
            file = new File(dirName);
            //不存在创建
            if (!file.exists()) {
                file.mkdirs();
            }
            //获取文件后缀名
            String fileNameFromUrl = NineGridViewImgUtils.getFileName(url);
            String type = fileNameFromUrl.substring(fileNameFromUrl.lastIndexOf(".") + 1);
            //下载后的文件名
            fileName = dirName + System.currentTimeMillis() + "." + type;
            File file1 = new File(fileName);
            if (file1.exists()) {
                file1.delete();     //不能有同名文件
            }
            //创建字节流
            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(fileName);
            //写数据
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            //完成后关闭流
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + dirName)));
    }
}
